package main

import (
	"fmt"
	"net"
	"sync"
)

type Server struct {
	Ip        string
	Port      int
	OnlineMap map[string]*User
	maplock   sync.RWMutex
	Message   chan string
}

func NewServer(ip string, port int) *Server {
	return &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
}

func (s *Server) ListenMessager() {
	for {
		msg := <-s.Message
		s.maplock.Lock()
		for _, el := range s.OnlineMap {
			el.C <- msg
		}
		s.maplock.Unlock()
	}
}

func (s *Server) BroadCase(user *User, msg string) {
	sendMsg := "[" + user.Addr + "]" + user.Name + ":" + msg
	s.Message <- sendMsg
}

func (s *Server) Handler(conn net.Conn) {
	fmt.Println("enter handler")
	// 上线的用户加入到onlineMap中，map是线程不安全的，所以需要加上锁
	user := NewUser(conn)
	s.maplock.Lock()
	s.OnlineMap[user.Name] = user
	s.maplock.Unlock()

	// 广播当前上线的用户
	s.BroadCase(user, "上线了")

	select {}
}

func (s *Server) Start() {
	// 创建tcp服务
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", s.Ip, s.Port))
	if err != nil {
		return
	}
	defer listen.Close()

	go s.ListenMessager()

	for {
		//accept
		conn, err := listen.Accept()
		if err != nil {
			continue
		}
		// do handle
		go s.Handler(conn)

	}
}
